package com.example.stray_animal_management_system.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.stray_animal_management_system.entity.User;
import com.example.stray_animal_management_system.mapper.UserMapper;
import com.example.stray_animal_management_system.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: panpan
 * @time: 2025/10/26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public User register(User user) {
        // 检查用户名是否存在
        User exist = getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (exist != null) {
            throw new RuntimeException("用户名已存在！");
        }
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRoleId(1); // 默认注册为普通用户
        save(user);
        return user;
    }

    @Override
    public User login(String username, String password) {
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("用户名或密码错误！");
        }
        return user;
    }
    @Override
    public boolean checkPassword(User user, String password) {
        return passwordEncoder.matches(password, user.getPassword());
    }

}